#include "channelwidget.h"
#include "globalconfig.h"


constexpr std::array<uint8_t, 4> MUS_ARRAY = {
    MUS_CH1,
    MUS_CH2,
    MUS_CH3,
    MUS_CH4
};

constexpr std::array<uint8_t, 8> OUT_ARRAY = {
    OUT_CH1,
    OUT_CH2,
    OUT_CH3,
    OUT_CH4,
    OUT_CH5,
    OUT_CH6,
    OUT_CH7,
    OUT_CH8
};

ChannelWidget::ChannelWidget(const IOWidget::Type &type, const stDevCfg &cfg, const stDevLimt &limt, QWidget *parent)
    : ATabWidget{parent}
    , m_type{type}
{
    if (type == IOWidget::Input) {
        size_t size = limt.tru_ch < MUS_ARRAY.size() ? limt.tru_ch : MUS_ARRAY.size();
        for (size_t i = 0; i < size; ++i) {
            auto widget = new IOWidget(type, MUS_ARRAY.at(i), cfg, limt, this);
            widget->set(GlobalConfig::getInstance().paramGroup().MusCh[i]);
            addTab(widget, GlobalConfig::getInstance().cfgName().mus[i]);
        }
        connect(&GlobalConfig::getInstance(), &GlobalConfig::loaded, this, [=]() {
            int size = count() < MAX_CH_MUS ? count() : MAX_CH_MUS;
            for (int i = 0; i < size; ++i) {
                auto w = qobject_cast<IOWidget*>(widget(i));
                if (w) {
                    w->set(GlobalConfig::getInstance().paramGroup().MusCh[i]);
                }
            }
        });
    }
    else if (type == IOWidget::Output) {
        size_t size = limt.tru_ch < OUT_ARRAY.size() ? limt.tru_ch : OUT_ARRAY.size();
        for (size_t i = 0; i < size; ++i) {
            auto widget = new IOWidget(type, OUT_ARRAY.at(i), cfg, limt, this);
            widget->set(GlobalConfig::getInstance().paramGroup().OutCh[i]);
            addTab(widget, GlobalConfig::getInstance().cfgName().out[i]);
        }
        connect(&GlobalConfig::getInstance(), &GlobalConfig::loaded, this, [=]() {
            int size = count() < MAX_CH_OUT ? count() : MAX_CH_OUT;
            for (int i = 0; i < size; ++i) {
                auto w = qobject_cast<IOWidget*>(widget(i));
                if (w) {
                    w->set(GlobalConfig::getInstance().paramGroup().OutCh[i]);
                }
            }
        });
    }
}

IOWidget::Type ChannelWidget::type() const
{
    return m_type;
}

